<script setup lang="ts">
import { computed, nextTick, ref, toRef, watch } from "vue";
import { TransitionPresets, executeTransition } from "@vueuse/core";
import {
  Position,
  BaseEdge,
  useVueFlow,
  useNodesData,
  getSmoothStepPath,
  EdgeLabelRenderer
} from "@vue-flow/core";

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  source: {
    type: String,
    required: true
  },
  target: {
    type: String,
    required: true
  },
  sourceX: {
    type: Number,
    required: true
  },
  sourceY: {
    type: Number,
    required: true
  },
  targetX: {
    type: Number,
    required: true
  },
  targetY: {
    type: Number,
    required: true
  },
  sourcePosition: {
    type: String,
    default: Position.Right
  },
  targetPosition: {
    type: String,
    default: Position.Left
  }
});

const { findEdge } = useVueFlow();

const nodesData = useNodesData([props.target, props.source]);

const edgePoint = ref(0);

const edgeRef = ref();

const labelPosition = ref({ x: 0, y: 0 });

const currentLength = ref(0);

const targetNodeData = toRef(() => nodesData.value[0].data);

const sourceNodeData = toRef(() => nodesData.value[1].data);

const isFinished = toRef(() => sourceNodeData.value.isFinished);

const isCancelled = toRef(() => targetNodeData.value.isCancelled);

const isAnimating = ref(false);

const edgeColor = toRef(() => {
  if (targetNodeData.value.hasError) {
    return "#f87171";
  }

  if (targetNodeData.value.isFinished) {
    return "#6b7280";
  }

  if (targetNodeData.value.isCancelled || targetNodeData.value.isSkipped) {
    return "#fbbf24";
  }

  if (targetNodeData.value.isRunning) {
    return "#2563eb";
  }
  if (isAnimating.value) {
    return "#2563eb"; // 动画时永远是蓝色线
  }

  return "#6b7280";
});


const path = computed(() => getSmoothStepPath(props));

watch(isCancelled, isCancelled => {
  if (isCancelled) {
    reset();
  }
});

watch(isAnimating, isAnimating => {
  const edge = findEdge(props.id);

  if (edge) {
    edge.data = {
      ...edge.data,
      isAnimating
    };
  }
});

watch(edgePoint, point => {
  const pathEl = edgeRef.value?.pathEl;

  if (!pathEl || point === 0 || !isAnimating.value) {
    return;
  }

  const nextLength = pathEl.getTotalLength();

  if (currentLength.value !== nextLength) {
    runAnimation();
    return;
  }

  labelPosition.value = pathEl.getPointAtLength(point);
});

watch(isFinished, isFinished => {
  if (isFinished) {
    runAnimation();
  }
});

async function runAnimation() {
  const pathEl = edgeRef.value?.pathEl;

  if (!pathEl) {
    return;
  }

  const totalLength = pathEl.getTotalLength();

  const from = edgePoint.value || 0;

  labelPosition.value = pathEl.getPointAtLength(from);

  isAnimating.value = true;

  if (currentLength.value !== totalLength) {
    currentLength.value = totalLength;
  }

  await executeTransition(edgePoint, from, totalLength, {
    transition: TransitionPresets.easeInOutCubic,
    duration: Math.max(1500, totalLength / 2),
    abort: () => !isAnimating.value
  });
  

  reset();
 
}

function reset() {
  nextTick(() => {
    edgePoint.value = 0;
    currentLength.value = 0;
    labelPosition.value = { x: 0, y: 0 };
    isAnimating.value = false;
  });
}

</script>

<template>
  <BaseEdge
    :id="id"
    ref="edgeRef"
    :path="path[0]"
    :style="{ stroke: edgeColor,strokeWidth: 15,strokeDasharray: '15,15', 
              strokeLinecap: 'round' }"  
  />/*线的定义*/

  <EdgeLabelRenderer v-if="isAnimating">
    <div
      :style="{
        transform: `translate(-50%, -50%) translate(${labelPosition.x}px,${labelPosition.y}px)`
      }"
      class="nodrag nopan animated-edge-label"
    >
      <span class="truck">
        <!-- <span class="box">📦</span> -->
        <svg class="box" width="50" height="50" xmlns="http://www.w3.org/2000/svg" >
          <defs>
            <!-- 定义渐变 -->
            <linearGradient id="metallic-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
              <stop offset="0%" style="stop-color:#b0b0b0;stop-opacity:1" />
              <stop offset="50%" style="stop-color:#d0d0d0;stop-opacity:1" />
              <stop offset="100%" style="stop-color:#b0b0b0;stop-opacity:1" />
            </linearGradient>

            <!-- 阴影效果 -->
            <filter id="f1" x="0" y="0" width="150%" height="150%">
              <feGaussianBlur in="SourceAlpha" stdDeviation="4" result="blur"/>
              <feOffset in="blur" dx="5" dy="5" result="offsetblur"/>
              <feFlood flood-color="rgba(0, 0, 0, 0.6)" result="color"/>
              <feComposite in2="offsetblur" operator="in"/>
              <feComposite in2="SourceAlpha" operator="in" result="shadow"/>
              <feComposite in="SourceGraphic" in2="shadow" operator="over"/>
            </filter>
          </defs>

          <!-- 第一层：上方略微偏亮的层 -->
          <rect x="10" y="10" width="80" height="80" rx="15" ry="15" fill="url(#metallic-gradient)" filter="url(#f1)" />

          <!-- 第二层：下方深一点的层 -->
          <rect x="5" y="5" width="80" height="80" rx="15" ry="15" fill="url(#metallic-gradient)" opacity="0.8" />
        </svg>
        <!-- 🚚 -->
        <svg xmlns="http://www.w3.org/2000/svg" width="70" height="70" viewBox="0 0 48 32" fill="none">
          <!-- 车身 -->
          <rect x="4" y="8" width="40" height="16" rx="2" ry="2" stroke="blue" stroke-width="2" fill="blue"/>
          <!-- 左轮 -->
          <circle cx="14" cy="26" r="4" stroke="#000" stroke-width="2" fill="orange"/>
          <!-- 右轮 -->
          <circle cx="34" cy="26" r="4" stroke="#000" stroke-width="2" fill="orange"/>
        </svg>
        
      </span>
    </div>
  </EdgeLabelRenderer>
</template>

<style scoped>
.animated-edge-label {
  position: absolute;
  z-index: 100;
}

.truck {
  position: relative;
  display: inline-block;
  transform: scaleX(-1);
  font-size: 48px;
}

.box {
  position: absolute;
  top: -20px;
  left: 5px;
  font-size: 25px; /* 单独控制图标大小 */
}
</style>
